package com.zhiyou100.video.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zhiyou100.video.model.User;
import com.zhiyou100.video.service.UserService;

@Controller
@RequestMapping("/front")
public class UserController {
	@Autowired
	private UserService us;

	@RequestMapping(value="/user/login")
	@ResponseBody
	public Map<String, Object> login(@RequestParam("email") String email,@RequestParam("password") String password,HttpServletResponse response,HttpSession session){
		Map<String, Object> usermaps = new HashMap<>();
		usermaps.put("email", email);
		usermaps.put("password", DigestUtils.md5Hex(password.getBytes()));
		User user = us.selectUser(usermaps);
		Map<String, Object> maps = new HashMap<>();
		if(user == null){
			maps.put("message", "用户不存在或者密码错误！请重新输入");
		}else{
			session.setAttribute("_front_user", user);
			maps.put("success", "true");
		}
		return maps;
	}


	@RequestMapping(value="/user/index.do")
	public String index(HttpSession session,Model model) {
		User user =(User) session.getAttribute("_front_user");
		model.addAttribute("user", user);
		return "forward:/front/user/index.jsp";
	}


	@RequestMapping("/user/logout.do")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/";
	}


	@RequestMapping(value="/user/regist.do")
	@ResponseBody
	public Map<String, Object> regist(User user,HttpServletResponse response,HttpSession session){
		User u = us.selectUserByEmail(user.getEmail());
		Map<String, Object> maps = new HashMap<>();
		if(u != null){
			maps.put("message", "邮箱已被注册！请重新输入");
		}else{
			Date date = new Date();
			user.setInsert_time(date);
			user.setPassword(DigestUtils.md5Hex(user.getPassword().getBytes()));
			int i = us.insertUser(user);
			if(i>0) {
				session.setAttribute("_front_user", user);
				maps.put("success", true);
			}else {
				maps.put("message", "注册失败！请重新输入");
			}
		}
		return maps;
	}


	@RequestMapping(value="/user/profile.do")
	public String onprofile(HttpSession session,Model mode,HttpServletRequest request,HttpServletResponse response) {
		User user =(User) session.getAttribute("_front_user");
		mode.addAttribute("user", user);
		return "forward:/front/user/profile.jsp";
	}

	@RequestMapping(value="/user/profile1.do")
	public String profile(User user,Model mode,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		Date date = new Date();
		user.setUpdate_time(date);
		int i = us.updateUser(user);
		if(i>0) {
			User u = us.selectUserByEmail(user.getEmail());
			session.setAttribute("_front_user", u);
			return "forward:/front/user/index.jsp";
		}
		return "forward:/front/user/profile.jsp";

	}


	@RequestMapping(value="/user/avatar.do")
	public String avatar(HttpSession session,Model mode,HttpServletRequest request,HttpServletResponse response) {
		User user =(User) session.getAttribute("_front_user");
		mode.addAttribute("user", user);
		return "forward:/front/user/avatar.jsp";
	}

	@RequestMapping(value="/user/avatar1.do")
	public String image_file(User user,Model mode,HttpServletResponse response,HttpSession session,MultipartFile image_file,HttpServletRequest request) throws IOException{
		Date date = new Date();
		user.setUpdate_time(date);
		InputStream is=image_file.getInputStream();
		String path=request.getServletContext().getRealPath("/static/img");
		System.out.println(path);
		String name = image_file.getOriginalFilename();//获取文件的名字
		String finalName = this.getFileName(name);
		File file = new File(path, finalName);
		OutputStream os = new FileOutputStream(file);
		IOUtils.copy(is, os);
		os.close();
		is.close();
		user.setHead_url(finalName);
		user.setEmail(((User)session.getAttribute("_front_user")).getEmail());
		int i = us.updateUser(user);
		if(i>0) {
			User u = us.selectUserByEmail(user.getEmail());
			session.setAttribute("_front_user", u);
			return "forward:/front/user/index.jsp";
		}else {
			return "forward:/front/user/avatar.jsp";
		}
	}
	private String getFileName(String filename) {
		String extension=FilenameUtils.getExtension(filename);
		return UUID.randomUUID().toString()+"."+extension;
	}


	@RequestMapping(value="/user/password.do")
	public String password(HttpSession session,Model mode,HttpServletRequest request,HttpServletResponse response) {
		User user =(User) session.getAttribute("_front_user");
		mode.addAttribute("user", user);
		return "forward:/front/user/password.jsp";
	}

	@RequestMapping(value="/user/password1.do")
	public String password(@RequestParam String oldPassword,@RequestParam String newPassword,
			@RequestParam String newPasswordAgain,HttpSession session,Model model){
		String email = ((User)session.getAttribute("_front_user")).getEmail();

		User u = us.selectUserByEmail(email);
		
		Date date = new Date();
		u.setUpdate_time(date);
		
		if(oldPassword.equals("")){
			model.addAttribute("message", "旧密码未填写");
		}else if(!(DigestUtils.md5Hex(oldPassword.getBytes())).equals(u.getPassword())){ 
			model.addAttribute("message", "旧密码填写错误");
		}else if(newPassword.equals("")) {
			model.addAttribute("message", "新密码必须填写");
		}else if(oldPassword.equals(newPassword)) {
			model.addAttribute("message", "新密码与旧密码不能相同");
		}else if(!newPassword.equals(newPasswordAgain)){
			model.addAttribute("message", "两次密码必须输入一致");
		}else {
			u.setPassword(newPasswordAgain);
			u.setEmail(((User)session.getAttribute("_front_user")).getEmail());
			u.setPassword(DigestUtils.md5Hex(newPasswordAgain.getBytes()));
			int i = us.updateUser(u);
			if(i>0) {
				User user = us.selectUserByEmail(u.getEmail());
				session.setAttribute("_front_user", user);
				return "forward:/front/user/index.jsp";
			}
		}
		return "forward:/front/user/password.jsp";
	}
}
